package fu.capstone.hanoicityguide.presentation.fragment.transportation;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import fu.capstone.hanoicityguide.R;
import fu.capstone.hanoicityguide.business.bo.transport.TransportBO;
import fu.capstone.hanoicityguide.business.bo.transport.TransportBOImp;
import fu.capstone.hanoicityguide.business.model.Transportation;
import fu.capstone.hanoicityguide.common.utility.CycloDialog;
import fu.capstone.hanoicityguide.common.utility.TaxiDialog;
import fu.capstone.hanoicityguide.presentation.adapter.ListTransportAdapter;

@SuppressLint("ValidFragment")
public class ListTransportFragment extends Fragment implements
		SearchView.OnQueryTextListener, SearchView.OnCloseListener,
		FragmentManager.OnBackStackChangedListener {

	private TransportBO transportBO;
	private ArrayList<Transportation> arrTransport;
	private ListTransportAdapter transportAdapter = null;
	private ListView listTransport = null;
	private SearchView searchView;
	private String keyword;

	public ListTransportFragment() {
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View listPlaceFragment = inflater.inflate(
				R.layout.fragment_list_transport, container, false);
		// init
		try {

			transportBO = new TransportBOImp(container.getContext());
			listTransport = (ListView) listPlaceFragment
					.findViewById(R.id.listTransport);

			// set sorter
			setKeyword("");

			// get all list attraction
			arrTransport = new ArrayList<Transportation>();
			arrTransport = transportBO.searchTransport(getKeyword());

			transportAdapter = new ListTransportAdapter(getActivity(),
					R.layout.adapter_list_transport, arrTransport);

			// set listview adapter and create event for items click
			listTransport.setAdapter(transportAdapter);

			listTransport.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					switch (arrTransport.get(position).getCategory().trim()) {
					case "Taxi":
						TaxiDialog calldialog = new TaxiDialog(parent
								.getContext());
						calldialog.showCallDialog(arrTransport.get(position)
								.getDesc());
						break;
					case "Cyclo":
						CycloDialog cycloDialog = new CycloDialog(parent
								.getContext());
						cycloDialog.showDialog(arrTransport.get(position)
								.getPhoneNumber(), arrTransport.get(position)
								.getWebsite());
						break;
					case "Bus":
						// TODO Auto-generated method stub
//						Fragment browseBus = new DetailBusFragment(arrTransport
//								.get(position).getId());
//						if (browseBus != null) {
//							FragmentManager fragmentManager = getFragmentManager();
//							FragmentTransaction fTransaction = fragmentManager
//									.beginTransaction();
//							fTransaction.addToBackStack("DetailBus");
//							fTransaction.replace(R.id.container, browseBus);
//							fTransaction.commit();
//						}
						break;

					default:
						break;
					}

				}
			});
			setHasOptionsMenu(true);
		} catch (Exception e) {
			Log.e("ListTransportFragment : ", e.toString());
		}

		return listPlaceFragment;
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

		// create option menu in actionbar
		inflater = getActivity().getMenuInflater();
		inflater.inflate(R.menu.list_searchtransport_menu, menu);

		// Associate searchable configuration with the SearchView
		searchView = (SearchView) menu.findItem(
				R.id.action_search_transportation).getActionView();
		setupSearchView();
		// get my MenuItem with placeholder submenu
		MenuItem searchMenuItem = menu
				.findItem(R.id.action_search_transportation);
		// Expand the search menu item in order to show by default the query
		searchMenuItem.expandActionView();

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// create event for items of option menu in actionbar
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onResume() {
		// on resume change the title of actionbar to Attractions
		super.onResume();
		getActivity().getActionBar().setTitle("Transportation");
	}

	public void setKeyword(String keyword) {
		this.keyword = keyword;
	}

	public String getKeyword() {
		return this.keyword;
	}

	private void setupSearchView() {

		searchView.setIconifiedByDefault(false);
		searchView.setQueryHint("Transport Name");

		searchView
				.setOnQueryTextFocusChangeListener(new OnFocusChangeListener() {

					@Override
					public void onFocusChange(View v, boolean hasFocus) {
						// TODO Auto-generated method stub
						if (hasFocus) {
							// drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
						} else if (!hasFocus) {
							onClose();
							// FragmentManager fm = getFragmentManager();
							// if (fm.getBackStackEntryCount() == 1) {
							// fm.popBackStackImmediate();
							// }
							// getFragmentManager().popBackStackImmediate();
						} else {
							onClose();
						}
					}
				});

		searchView.setOnQueryTextListener(this);
		searchView.setOnCloseListener(this);
	}

	@Override
	public boolean onQueryTextSubmit(String query) {
		setKeyword(query);
		if (getKeyword() != null) {
			arrTransport = transportBO.searchTransport(getKeyword());
			transportAdapter.setArr(arrTransport);
			transportAdapter.notifyDataSetChanged();
			return true;
		} else {
			return false;
		}
	}

	@Override
	public boolean onQueryTextChange(String newText) {
		// TODO Auto-generated method stub
		setKeyword(newText);
		if (getKeyword() != null) {
			arrTransport = transportBO.searchTransport(getKeyword());
			transportAdapter.setArr(arrTransport);
			transportAdapter.notifyDataSetChanged();
			return true;
		} else {
			return false;
		}

	}

	@Override
	public boolean onClose() {
		// TODO Auto-generated method stub
		// drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
		searchView.setQuery("", true);
		setKeyword("");
		FragmentManager fManager = getFragmentManager();
		FragmentTransaction fTransaction = fManager.beginTransaction();

		if (fManager.getBackStackEntryCount() < 2) {
			fManager.popBackStackImmediate();
		}
		// fManager.popBackStack("ListTransportation",
		// FragmentManager.POP_BACK_STACK_INCLUSIVE);

		// fTransaction.hide(getTargetFragment());
		// fTransaction.commit();
		return true;
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		searchView = null;
		super.onDestroy();
	}

	@Override
	public void onBackStackChanged() {
		// TODO Auto-generated method stub
		// Toast.makeText(
		// getActivity(),
		// "Count listFragment : "
		// + getFragmentManager().getBackStackEntryCount(),
		// Toast.LENGTH_SHORT).show();
	}

}
